package com.huarui.user.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.util.HttpUtil;
import org.ewaf.framework.util.MD5Digester;
import com.huarui.user.error.UserError;
import com.huarui.user.model.CookieConstants;
import com.huarui.user.model.User;
import com.huarui.user.service.UserService;
import com.huarui.util.PinyinToolkit;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * xzz
 * 
 * @author Administrator
 * 
 */
public class RegisterAction extends BaseAction {

	private static final long serialVersionUID = -1081475627097321668L;
	private Logger logger = Logger.getLogger(RegisterAction.class);
	private User user;
	private String password2;
	private UserService userService;
	private List<User> userList;
	private String activeCode;
	private String verifyCode;
	private String http_email;
	private String birthday;
	private String empEmail;
	private String invitorId;
	private XMemcachedClient  memcachedClient; 
    private String tokenName; 
	
	
	public void setMemcachedClient(XMemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	public String getEmpEmail() {
		return empEmail;
	}

	public void setEmpEmail(String empEmail) {
		this.empEmail = empEmail;
	}

	public String getInvitorId() {
		return invitorId;
	}

	public void setInvitorId(String invitorId) {
		this.invitorId = invitorId;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getHttp_email() {
		return http_email;
	}

	public void setHttp_email(String http_email) {
		this.http_email = http_email;
	}

	public String getVerifyCode() {
		return verifyCode;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String getActiveCode() {
		return activeCode;
	}

	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}
	public String getTokenName() {
		return tokenName;
	}

	public void setTokenName(String tokenName) {
		this.tokenName = tokenName;
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	public String input() {

		/**HttpServletRequest request = HttpUtil.getRequest();

		HttpServletResponse response = HttpUtil.getResponse();

		CookieManager cookie = new CookieManager(request);

		cookie.removeCookie(response, null, CookieConstants.Cookie_PATH,
				CookieConstants.COOKIE_PERM);*/
		    
		tokenName="true";
		return SUCCESS;
	}

	/**
	 * 注册
	 * 
	 * @return
	 * @throws MemcachedException 
	 * @throws InterruptedException 
	 * @throws TimeoutException 
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "password2", shortCircuit = true, key = "user.password2.required"),
			@RequiredStringValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.required"),
			@RequiredStringValidator(fieldName = "user.password", shortCircuit = true, key = "user.password.required"),
			@RequiredStringValidator(fieldName = "user.name", shortCircuit = true, key = "user.name.required") }, 
			emails = { @EmailValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.format.error") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "user.name", maxLength = "20", shortCircuit = true, key = "user.name.length.error"),
			@StringLengthFieldValidator(fieldName = "user.password", minLength = "6", shortCircuit = true, key = "user.password.length.minerror"),
			@StringLengthFieldValidator(fieldName = "password2", minLength = "6", shortCircuit = true, key = "user.password.length.minerror") }, fieldExpressions = { @FieldExpressionValidator(fieldName = "password2", expression = "password2==user.password", shortCircuit = true, key = "user.password2.same.error") })
	public String submit(){

		HttpServletRequest request = HttpUtil.getRequest();

		CookieManager cookie = new CookieManager(request);
		/**
		 * String indent15 = "^(\\d{6})(\\d{2})(\\d{2})(\\d{2})(\\d{3})$";
		 * 
		 * String ident18="^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])(\\d{3})(\\d|x|X)$"
		 * ;
		 * 	regexFields = { @RegexFieldValidator(fieldName = "user.ident", shortCircuit = false, expression = "(^(\\d{6})(\\d{2})(\\d{2})(\\d{2})(\\d{3})$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])(\\d{3})(\\d|x|X)$)", key = "user.ident.format.error") }
		 * if(!user.getIdent().matches(indent15)&&!user.getIdent().matches(
		 * ident18)){
		 * this.addFieldError("user.ident",UserError.USER_IDENT_FORMAT_ERROR
		 * .getChError()); return INPUT;
		 * 
		 * }
		 
		if(StringUtils.isNotBlank(birthday)){
		  user.setBirthday(DateFormatUtil.parseDate(birthday));
		}*/
		user.setPassword(MD5Digester.digest(user.getPassword()));
	
		String code = cookie.getValue(CookieConstants.COOKIE_CODE, "code");
		String checkCode="";
		try {
			checkCode = memcachedClient.get(code);
			
			memcachedClient.delete(code);
		} catch (TimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MemcachedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (!StringUtils.trim(verifyCode).equalsIgnoreCase(checkCode)) {
     
			this.addFieldError("verifyCode", UserError.VERIFYCODE_WRONG
					.getChError());

			return INPUT;
		}
		
		// 验证成功后删除关于验证码的cookie
		cookie.removeCookie(httpServletResponse, null,
				CookieConstants.Cookie_PATH, CookieConstants.COOKIE_CODE);

		User u = userService.getUserByEmail(user.getEmail());

		if (u != null) {

			this.addFieldError("user.email", UserError.DUPLICATED_EMAIL
					.getChError());

			return INPUT;
		}

		/**User uIdent = userService.getUserByIdent(user.getIdent());

		if (uIdent != null) {

			this.addFieldError("user.ident", UserError.DUPLICATED_IDENT
					.getChError());

			return INPUT;

		}*/

		activeCode = UUID.randomUUID().toString();

		user.setActivateCode(activeCode);
		
		user.setPyCode(PinyinToolkit.cn2FirstSpell(user.getName()));
		
		user.setCompanyId(0);
		try {

			userService.create(user);

		} catch (Exception e) {

			throw new RuntimeException(e.getMessage());
		}
		userService.sendActiveEmail(user);

		http_email="http://mail."+user.getEmail().substring(user.getEmail().indexOf("@")+1);
		
		 if(http_email.equals("http://mail.gmail.com")){
			 
			 http_email="http://mail.google.com";
			 
		 }
		
		
		return SUCCESS;
	}

	/**
	 * 激活用户
	 * 
	 * @return
	 */

	public String activeUserSubmit() {

		HttpServletRequest request = HttpUtil.getRequest();

		String activeCode = request.getParameter("activeCode");

		user = userService.getByActiveCode(activeCode);
       
		
	 try{	
		 
		userService.activeUser(user);
		
	 }catch (Exception e) {
		 
		 logger.debug(e.getMessage());
		 throw new RuntimeException(UserError.ACTIVE_FAILTURE.getChError());

	}
		return SUCCESS;

	}
	
	private PrintWriter grantWrite(){
		HttpServletResponse response = HttpUtil.getResponse();
		httpServletResponse.setContentType("text/plain; charset=UTF-8"); // 处理中文问题的必须的代码
		PrintWriter out=null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			
			logger.debug(e);
		}
		return out;
	}
	

	public String checkEmail() throws IOException {

		String email = HttpUtil.getRequest().getParameter("email");
		
		PrintWriter out=grantWrite();

		user = userService.getUserByEmail(email);

		if (user != null) {
			
			out.print(UserError.DUPLICATED_EMAIL.getChError());
		}
		
		return null;
	}

	public String checkIdent() throws IOException {

		String ident = HttpUtil.getRequest().getParameter("ident");

		PrintWriter out=grantWrite();

		user = userService.getUserByIdent(ident);

		if (user != null) {

			 out.print(UserError.DUPLICATED_IDENT.getChError());			 
		}

		return null;
	}

}
